<?php

/**
 * Account session model
 *
 * @package    Euso
 * @subpackage Model
 */
class Account_Model_Session
{
	// Holds account's session information
	protected static $_session = null;
	// Holds current session's account information
	protected static $_account = null;


	// Gets the information about the account in the session (logged in user)
	// Returns Account_Model_Account or null
	public static function getAccount()
	{
		if (self::$_account === NULL) {
			self::_loadAccount();
		}
		return self::$_account;
	}


	public static function beginSession($id)
	{
		if (intval($id) > 0) {
			self::$_account = Account_Model_Account::getInstanceById($id);

			if (self::$_account instanceof Account_Model_Account) {
				// Initialize the session
				self::getSession();

				// Store in the session
				self::$_session->id = $id;
				self::$_session->idname = self::$_account->getIdName();
				self::$_session->code = self::$_account->getCode();

				return true;
			}
		}

		return false;
	}
	public static function endSession($destroy = TRUE)
	{
		if (self::getSession() != NULL) {
			// Clear the session namespace
			Zend_Session::namespaceUnset(APPLICATION_SLUG .'.account');
			// Destroy all session informations
			if ($destroy === TRUE) {
				Zend_Session::destroy(true, true);
			}
		}

		self::$_account = NULL;
		self::$_session = NULL;
	}


	// Returns Zend_Session_Namespace
	public static function getSession()
	{
		if (self::$_session === NULL) {
			self::$_session = new Zend_Session_Namespace(APPLICATION_SLUG .'.account');
		}
		return self::$_session;
	}

	// Checks whether there's a valid session of account (logged in user)
	public static function hasValidSession()
	{
		$sess = self::getSession();
		return isset($sess) && $sess != NULL && intval($sess->id) > 0
			&& (isset($sess->code) || isset($sess->idname));
	}

	protected static function _loadAccount()
	{
		$sess = self::getSession();
		if (isset($sess) && $sess != NULL && intval($sess->id) > 0) {
			self::$_account = Account_Model_Account::getInstanceById($sess->id);
		} else {
			self::$_account = NULL;
		}
		return self::$_account;
	}
}